<?php

if (!defined('YAR_WEB_PAGE_TO_ROOT')) {
    die("系统错误：WEB_PAGE_TO_ROOT未定义.");
    exit;
}

session_start(); // Creates a 'Full Path Disclosure' vuln.

if (!file_exists(YAR_WEB_PAGE_TO_ROOT . 'config.php')) {
    die ("系统错误：配置文件未找到，复制config/config.inc.php.dist到config/config.inc.php并配置相关参数。");
}

// 包含配置文件
require_once YAR_WEB_PAGE_TO_ROOT . 'config.php';


// YAR 版本
function yarVersionGet()
{
    return 'V_0.0.1 YAR';
}

// YAR release 日期
function yarReleaseDateGet()
{
    return '2020-03-08';
}

// Start session functions --
function &yarSessionGrab()
{
    if (!isset($_SESSION['yar'])) {
        $_SESSION['yar'] = array();
    }
    return $_SESSION['yar'];
}

function yarLogin($pUsername)
{
    $yarSession =&yarSessionGrab();
    $yarSession['username'] = $pUsername;
}

function yarIsLoggedIn()
{
    $yarSession =&yarSessionGrab();
    return isset($yarSession['username']);
}


function yarLogout()
{
    $yarSession =&yarSessionGrab();
    unset($yarSession['username']);
}

function yarPageReload()
{
    yarRedirect($_SERVER['PHP_SELF']);
}

function yarCurrentUser()
{
    $yarSession =&yarSessionGrab();
    return (isset($yarSession['username']) ? $yarSession['username'] : '');
}

function yarSecurityLevelGet()
{
    return isset($_COOKIE['security']) ? $_COOKIE['security'] : 'impossible';
}


function yarSecurityLevelSet($pSecurityLevel)
{
    if ($pSecurityLevel == 'impossible') {
        $httponly = true;
    } else {
        $httponly = false;
    }
    setcookie(session_name(), session_id(), null, '/', null, null, $httponly);
    setcookie('security', $pSecurityLevel, NULL, NULL, NULL, NULL, $httponly);
}


// Start message functions --

function yarMessagePush($pMessage)
{
    $yarSession =&yarSessionGrab();
    if (!isset($yarSession['messages'])) {
        $yarSession['messages'] = array();
    }
    $yarSession['messages'][] = $pMessage;
}

function yarMessagePop()
{
    $yarSession =&yarSessionGrab();
    if (!isset($yarSession['messages']) || count($yarSession['messages']) == 0) {
        return false;
    }
    $pMessage = array_shift($yarSession['messages']);
    $yarSession['messages'] = array();
    return $pMessage;
}

function messagesPopAllToHtml()
{
    $messagesHtml = '';
    while (($message = yarMessagePop()) != "") {   // TODO- sharpen!
        $messagesHtml .= "<div class=\"message\">{$message}</div>";
    }
    return $messagesHtml;
}

$DBMS_errorFunc = "";

// Database 管理
if ($DBMS == 'MySQL') {
    $DBMS = htmlspecialchars(strip_tags($DBMS));
    $DBMS_errorFunc = 'mysqli_error()';
} elseif ($DBMS == 'PGSQL') {
    $DBMS = htmlspecialchars(strip_tags($DBMS));
    $DBMS_errorFunc = 'pg_last_error()';
} else {
    $DBMS = "No DBMS selected.";
    $DBMS_errorFunc = '';
}


function yarDatabaseConnect()
{
    global $_YAR;
    global $DBMS;
    //global $DBMS_connError;
    global $DBMS_errorFunc;
    global $db;

    if ($DBMS == 'MySQL') {
        if (!@($GLOBALS["___mysqli_ston"] = mysqli_connect($_YAR['db_server'].":".$_YAR['db_port'], $_YAR['db_user'], $_YAR['db_password']))
            || !@((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . $_YAR['db_database']))) {
            // var_dump($GLOBALS);
            yarLogout();
            yarMessagePush('数据库连接错误。' . $DBMS_errorFunc);
            yarRedirect(YAR_WEB_PAGE_TO_ROOT . 'setup.php');
        }else{
            $query = ("SELECT table_schema, table_name, create_time
				FROM information_schema.tables
				WHERE table_schema='{$_YAR['db_database']}' AND table_name='users'
				LIMIT 1");
            $result = @mysqli_query($GLOBALS["___mysqli_ston"],  $query );
            var_dump($result);
            if( mysqli_num_rows( $result ) != 1 ) {
                yarMessagePush( "数据库表不正确，需要重新安装。" );
                yarRedirect( YAR_WEB_PAGE_TO_ROOT . 'setup.php' );
            }
        }
        // MySQL PDO Prepared Statements (for impossible levels)
        $db = new PDO('mysql:host=' . $_YAR['db_server'] . ';dbname=' . $_YAR['db_database'] . ';charset=utf8', $_YAR['db_user'], $_YAR['db_password']);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    } elseif ($DBMS == 'PGSQL') {
        yarMessagePush('PostgreSQL目前还不支持。');
        yarPageReload();
    } else {
        die ("Unknown {$DBMS} selected.");
    }
}

function yarRedirect($pLocation)
{
    session_commit();
    header("Location: {$pLocation}");
    exit;
}

function checkToken($user_token, $session_token, $returnURL)
{  # Validate the given (CSRF) token
    if ($user_token !== $session_token || !isset($session_token)) {
        yarMessagePush('CSRF token 错误。');
        yarRedirect($returnURL);
    }
}

function generateSessionToken()
{  # Generate a brand new (CSRF) token
    if (isset($_SESSION['session_token'])) {
        destroySessionToken();
    }
    $_SESSION['session_token'] = md5(uniqid());
}

function destroySessionToken()
{  # Destroy any session with the name 'session_token'
    unset($_SESSION['session_token']);
}

function tokenField()
{  # Return a field for the (CSRF) token
    return "<input type='hidden' name='user_token' value='{$_SESSION[ 'session_token' ]}' />";
}

?>
